/**
 * 
 */
package uy.com.pzit.fpmundialmodel.dao;

import java.util.List;

import net.sf.ehcache.ObjectExistsException;

import org.apache.log4j.Logger;
import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.type.Type;

import uy.com.pzit.fpmundialmodel.dao.dbObjects.DBObject;
import uy.com.pzit.fpmundialmodel.dao.dbObjects.DBTemplate;
import uy.com.pzit.fpmundialmodel.domain.Pais;

/**
 * @author pferraz
 *
 */
public class PaisDAO {

	private static Logger logger=Logger.getLogger(PaisDAO.class);
	
	public Pais addPais(Pais pais) {
		return (DBObject.addObject(pais))?pais:null;
	}

	public Pais getPaisById(Integer id) {
		// TODO Auto-generated method stub
		return (Pais) DBObject.getObjectById(Pais.class, id);
	}

	

	@SuppressWarnings("unchecked")
	public Pais getPaisByNombre(String nombre) {
		Session sess = null;
		Pais result = null;
		try {
			sess = DBTemplate.getConnTemplate().getSessionFactory().openSession();
			Query query = sess.createQuery("from p in class uy.com.pzit.fpmundialmodel.domain.Pais where p.nombre=?");
			query.setParameters(new Object[] {nombre},new Type[]{Hibernate.STRING});
			List<Pais> list=query.list();
			if (list.isEmpty()) {
				throw new ObjectExistsException("No existen paises.");
			}else{
				result = list.get(0);
			}
		} catch (HibernateException e) {
			logger.error("Error al buscar paises", e);
		} finally {
			if (sess != null) {
				sess.close();
			}

		}
		return result;
	}
	
	public Pais updatePais(Pais pais) {
		return (DBObject.updateObject(pais))?pais:null;
	}

	@SuppressWarnings("unchecked")
	public List<Pais> getPaisesByOrder(String propiedad, String order) {
		Session sess = null;
		List<Pais> result = null;
		try {
			sess = DBTemplate.getConnTemplate().getSessionFactory().openSession();
			Query query = sess.createQuery("from p in class uy.com.pzit.fpmundialmodel.domain.Pais order by p."+propiedad+" "+order);
			result = query.list();
			if (result.isEmpty()) {
				throw new ObjectExistsException("No existen paises.");
			}
		} catch (HibernateException e) {
			logger.error("Error al buscar paises", e);
		} finally {
			if (sess != null) {
				sess.close();
			}

		}
		return result;
	}

	public void executeQuery(String query) {
		
		DBObject.txInsertUpdateDelete(query);
	}

	public void executePureQuery(String[] query) {
		DBObject.executePureQuery(query);
	}

	
	

}
